var $_GET = (function () {
    var url = window.document.location.href.toString();
    var u = url.split("?");
    if (typeof (u[1]) == "string") {
        u = u[1].split("&");
        var get = {};
        for (var i in u) {
            var j = u[i].split("=");
            get[j[0]] = j[1];
        }
        return get;
    } else {
        return {};
    }
})();

// HTML编码解码

function escape2Html(str) {
    var arrEntities={'lt':'<','gt':'>','nbsp':' ','amp':'&','quot':'"'};
    return str.replace(/&(lt|gt|nbsp|amp|quot);/ig,function(all,t){return arrEntities[t];});
}

function html2Escape(sHtml) {
    return sHtml.replace(/[<>&"]/g,function(c){return {'<':'&lt;','>':'&gt;','&':'&amp;','"':'&quot;'}[c];});
}

$(function () {
    var activityid = $_GET['id'];

    $("#jqGrid").jqGrid({
        url: baseURL + 'sys/activity/foundByActivityId?id='+activityid,
        datatype: "json",
        colModel: [			
			{ label: 'ID', name: 'tbActivityCommodity.id', index: 'tbActivityCommodity.id', width: 50, key: true },
            { label: '商品ID', name: 'tbCommodity.id', index: 'tbCommodity.id', width: 80 },
            { label: '商品名称', name: 'tbCommodity.commodityname', index: 'tbCommodity.commodityname', width: 80 },
			{ label: '商品编号', name: 'tbCommodity.commoditynum', index: 'tbCommodity.commoditynum', width: 80 },
			{ label: '分类名称', name: 'tbCommodity.categoryname', index: 'tbCommodity.categoryname', width: 80 },
            { label: '普通价格', name: 'tbCommodity.price', index: 'tbCommodity.price', width: 80,formatter:function(value,options,row){
                return value/100;
            }},
            { label: '会员价', name: 'tbCommodity.pricediscounts', index: 'tbCommodity.pricediscounts', width: 80,formatter:function(value,options,row){
                return value/100;
            } },
            { label: '销量', name: 'tbCommodity.salesnum', index: 'tbCommodity.salesnum', width: 80 },
            { label: '活动价', name: 'tbActivityCommodity.nowprice', index: 'tbActivityCommodity.nowprice', width: 80,formatter:function(value,options,row){
                return value/100;
            } },
            { label: '销量', name: 'tbActivityCommodity.reserve', index: 'tbActivityCommodity.reserve', width: 80 },
            { label: '库存', name: 'tbActivityCommodity.totalStore', index: 'tbActivityCommodity.totalStore', width: 80 },
            { label: '邮费', name: 'tbCommodity.freight', index: 'tbCommodity.freight', width: 80,formatter:function(value,options,row){
                return value/100;
            } },
            //
            // { label: '新品', name: 'isnew', index: 'isNew', width: 80 ,formatter: function (value, options, row) {
            //     return value === false ?
            //         '<span class="label label-danger">否</span>' :
            //         '<span class="label label-success">是</span>';
            // }},
            // { label: '推荐', name: 'isrecommend', index: 'isRecommend', width: 80 ,formatter: function (value, options, row) {
            //     return value === false ?
            //         '<span class="label label-danger">否</span>' :
            //         '<span class="label label-success">是</span>';
            // }},
            // { label: '热门', name: 'ishot', index: 'isHot', width: 80 ,formatter: function (value, options, row) {
            //     return value === false ?
            //         '<span class="label label-danger">否</span>' :
            //         '<span class="label label-success">是</span>';
            // }},
            // { label: '明星商品', name: 'celebrity', index: 'celebrity', width: 80 ,formatter: function (value, options, row) {
            //     return value === false ?
            //         '<span class="label label-danger">否</span>' :
            //         '<span class="label label-success">是</span>';
            // }},
            // { label: '优选商品', name: 'preferred', index: 'preferred', width: 80 ,formatter: function (value, options, row) {
            //     return value === false ?
            //         '<span class="label label-danger">否</span>' :
            //         '<span class="label label-success">是</span>';
            // }}
        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "listdto",
            // page: "page.current",
            // total: "page.pages",
            // records: "page.total"
        },
        prmNames : {
            // page:"page",
            // rows:"limit",
            // order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
});

var vm = new Vue({
	el:'#rrapp',
	data:{
		q:{
            commodityname : "加载中"
		},
		showList: true,
		title: null,
		commodity: {
            picurl:null
        },
        allGoodsList:[],
        activity:{},
        sels: [],
        addPostData:{
		    price:0,
            totalStore:0,
            commodityid:0,
        },
        tbActivityCommodity:{
		    activityid:0,
            nowprice:0,
            totalStore:0,
            commodiytid:0,
        }
	},
    created: function () {
        // 获取id
        var activityid = $_GET['id'];
        if (!activityid) {
            alert('系统错误,没有获取到活动ID,请返回重试.');
            return false;
        }


        $.get(baseURL + "sys/activity/info/"+activityid , function (r) {
            vm.activity = r.activity;
        })
    },
	methods: {
	    getAllGoodsList:function () {
            var url = "sys/commodity/findAll";
            $.ajax({
                type: "GET",
                url: baseURL + url,
                contentType: "application/json",
                // data: JSON.stringify(vm.addPostData),
                success: function(r){
                    if(r.code === 0){
                        vm.allGoodsList = r.list
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        handleNum:function () {
            if(vm.addPostData.price < 0){
                vm.addPostData.price = 0;
            }

            if(vm.addPostData.totalStore < 0){
                vm.addPostData.totalStore = 0;
            }
        },
        changeImage: function(e) {
            var file = e.target.files[0]
            var reader = new FileReader()
            var THIS = this
            reader.readAsDataURL(file)
            reader.onload = function(e) {
                // this.result 为图片
                THIS.upload(this.result)
            }
        },
        saveOrUpdate: function (event) {
            vm.tbActivityCommodity.commodiytid = vm.addPostData.commodityid,
            vm.tbActivityCommodity.activityid = vm.activity.id,
            vm.tbActivityCommodity.nowprice = vm.addPostData.price,
            vm.tbActivityCommodity.totalStore = vm.addPostData.totalStore
            var url = vm.addPostData.id == null ? "sys/activity/addCommodity" : "sys/activity/addCommodity";
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: JSON.stringify(vm.tbActivityCommodity),
                success: function(r){
                    if(r.code === 0){
                        alert('操作成功', function(index){
                            vm.reload();
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
		query: function () {
			vm.reload();
		},
		add: function(event){
            // 添加商品
            vm.showList = false;
            vm.title = "添加商品到活动";

            //加载所有商品列表
            vm.getAllGoodsList()

            // 清空原有数据
		},
		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "sys/activity/delCommodity",
				    contentType: "application/json",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getUeditor: function () {
            var ue = UE.getEditor('container');
            var _html = ue.getContent();
            return _html
        },
		getInfo: function(id){
			$.get(baseURL + "sys/commodity/info/"+id, function(r){
			    r.commodity.commoditydetails = escape2Html(r.commodity.commoditydetails )
                window.ue.setContent(r.commodity.commoditydetails);
                vm.commodity = r.commodity;
            });
		},
		reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam','page');
            $("#jqGrid").jqGrid('setGridParam',{
                postData:{'commodityname': vm.q.commodityname},
                page:page
            }).trigger("reloadGrid");
		},
        back() {
            window.history.go(-1);
        }
	}
});